package com.atguigu.flink.chapter05.transform;

import org.apache.flink.api.common.functions.RichMapFunction;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;

/**
 * @Author lzc
 * @Date 2022/7/4 14:11
 */
public class Flink01_Map {
    public static void main(String[] args) {
        Configuration conf = new Configuration();
        conf.setInteger("rest.port", 2000);
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(conf);
        env.setParallelism(2);
        
        DataStreamSource<Integer> stream = env.fromElements(10, 20, 30, 40, 50);
        
        
        /*stream
            .map(new MapFunction<Integer, Integer>() {
                @Override
                public Integer map(Integer value) throws Exception {
                    return value * value;
                }
            })
            .print();*/
       /* stream
            .map( value -> value * value)
            .print();*/
        
        stream
            .map(new RichMapFunction<Integer, Integer>() {
                @Override
                public void open(Configuration parameters) throws Exception {
                    // 每个并行度执行一次, 在程序启动的时候执行
                    // 做一些初始化的工作, 比如建立到数据库连接
                    System.out.println("打开连接");
                }
                
                @Override
                public void close() throws Exception {
                    // 当程序关闭的时候执行,
                    System.out.println("关闭连接");
                }
                
                @Override
                public Integer map(Integer value) throws Exception {
                    // 建立到数据库的连接
                    
                    // 查询数据
                    
                    // 关闭连接
                    
                    return value;
                }
            })
            .print();
        
        
        try {
            env.execute();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
